{% extends "teacher/teacher_base.html" %}

{% block title %}班级信息 - {{ classes.class_name }}{% endblock %}

{% block content %}
    <div class="p-4 md:p-6 lg:p-8">
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <!-- 班级信息头部 -->
            <div class="p-6 border-b border-gray-100 bg-gradient-to-r from-blue-50 to-indigo-50">
                <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div>
                        <h1 class="text-2xl font-bold text-gray-800">{{ classes.class_name }}班</h1>
                        <p class="text-gray-600">
                            专业：{{ classes.major }} | 年级：{{ classes.grade }} |
                            班主任：{% if classes.advisor %}{{ classes.advisor.username }}{% else %}未指定{% endif %} |
                            班长：{% if classes.monitor %}{{ classes.monitor.username }}{% else %}未指定{% endif %}|
                            学生人数：{{ classes.students|length }}人
                        </p>
                    </div>
                    <div class="flex gap-3">
                        <button id="saveBtn"
                                class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors flex items-center"
                                >
                            <i class="fa fa-save mr-2"></i> 保存修改
                        </button>
                    </div>
                </div>
            </div>

            <!-- 班级描述（可点击编辑） -->
            <!-- 班级描述（始终可编辑） -->
            <div class="p-6 border-b border-gray-100">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700">班级描述</label>
                    <div class="mt-1">
                        <!-- 只读视图（隐藏） -->
                        <div id="descView" class="p-2 border border-gray-200 rounded-md bg-gray-50 hidden">
                            {{ classes.description | default('暂无班级描述') }}
                        </div>

                        <!-- 编辑视图（始终显示） -->
                        <textarea id="descEdit"
                                  class="w-full p-2 border border-gray-300 rounded-md bg-white shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                  rows="3">{{ classes.description | default('') }}</textarea>
                    </div>
                </div>
            </div>

            <!-- 班级统计卡片 -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 p-6">
                <!-- 出勤率 -->
                <div class="bg-white rounded-lg shadow-sm border border-gray-100 p-5 hover:shadow-md transition-shadow">
                    <div class="flex justify-between items-center mb-4">
                        <div>
                            <p class="text-sm text-gray-500">出勤率</p>
                            <h3 class="text-2xl font-bold text-gray-800">{{ attendance_rate }}%</h3>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
                            <i class="fa fa-check-circle text-blue-500 text-xl"></i>
                        </div>
                    </div>
                    <div class="h-1.5 bg-gray-200 rounded-full">
                        <div class="h-full bg-blue-500 rounded-full" style="width: {{ attendance_rate }}%"></div>
                    </div>
                </div>

                <!-- 作业完成率 -->
                <div class="bg-white rounded-lg shadow-sm border border-gray-100 p-5 hover:shadow-md transition-shadow">
                    <div class="flex justify-between items-center mb-4">
                        <div>
                            <p class="text-sm text-gray-500">作业完成率</p>
                            <h3 class="text-2xl font-bold text-gray-800">{{ homework_rate }}%</h3>
                        </div>
                        <div class="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center">
                            <i class="fa fa-file-check text-green-500 text-xl"></i>
                        </div>
                    </div>
                    <div class="h-1.5 bg-gray-200 rounded-full">
                        <div class="h-full bg-green-500 rounded-full" style="width: {{ homework_rate }}%"></div>
                    </div>
                </div>

                <!-- 活动参与率 -->
                <div class="bg-white rounded-lg shadow-sm border border-gray-100 p-5 hover:shadow-md transition-shadow">
                    <div class="flex justify-between items-center mb-4">
                        <div>
                            <p class="text-sm text-gray-500">活动参与率</p>
                            <h3 class="text-2xl font-bold text-gray-800">{{ activity_rate }}%</h3>
                        </div>
                        <div class="w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center">
                            <i class="fa fa-users text-purple-500 text-xl"></i>
                        </div>
                    </div>
                    <div class="h-1.5 bg-gray-200 rounded-full">
                        <div class="h-full bg-purple-500 rounded-full" style="width: {{ activity_rate }}%"></div>
                    </div>
                </div>

                <!-- 班级活跃度 -->
                <div class="bg-white rounded-lg shadow-sm border border-gray-100 p-5 hover:shadow-md transition-shadow">
                    <div class="flex justify-between items-center mb-4">
                        <div>
                            <p class="text-sm text-gray-500">班级活跃度</p>
                            <h3 class="text-2xl font-bold text-gray-800">{{ activity_level }}</h3>
                        </div>
                        <div class="w-12 h-12 bg-yellow-100 rounded-full flex items-center justify-center">
                            <i class="fa fa-heartbeat text-yellow-500 text-xl"></i>
                        </div>
                    </div>
                    <div class="h-1.5 bg-gray-200 rounded-full">
                        <div class="h-full bg-yellow-500 rounded-full"
                             style="width: {{ activity_level_percent }}%"></div>
                    </div>
                </div>
            </div>

            <!-- 学生名单 -->
            <div class="p-6 border-t border-gray-100">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="text-xl font-semibold text-gray-800">学生名单</h2>
                </div>

                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                        <tr>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                学号
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                姓名
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                性别
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                专业
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                联系电话
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                班长
                            </th>
                        </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                        {% for student in students %}
                            <tr class="hover:bg-gray-50 transition-colors">
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ student.student_no }}</td>
                                <td class="px-6 py-4 whitespace-nowrap flex items-center gap-3">{{ student.username }}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ student.gender }}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ student.major }}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ student.telephone | default('未填写') }}</td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <label class="inline-flex items-center cursor-pointer">
                                        <input type="radio" name="monitor" value="{{ student.id }}"
                                               class="w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-500"
                                               {% if student.id == classes.monitor_id %}checked{% endif %}
                                        >
                                        <span class="ml-2 text-sm text-gray-700">设为班长</span>
                                    </label>
                                    {% if student.id == classes.monitor_id %}
                                        <span class="ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
                                    现任
                                </span>
                                    {% endif %}
                                </td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <!-- 脚本部分 -->
    </div>
    {#    <script src="{{ url_for('static',filename='js/teacher_js/class_message.js') }}"></script>#}
    <script>
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const descEdit = document.getElementById('descEdit');
    const saveBtn = document.getElementById('saveBtn');
    const classId = {{ classes.id }}; // 从模板获取班级ID

    // 启用保存按钮（移除disabled属性）
    saveBtn.removeAttribute('disabled');

    // 隐藏只读视图，显示编辑框
    document.getElementById('descView').style.display = 'none';
    descEdit.classList.remove('hidden');
    descEdit.removeAttribute('style'); // 移除内联样式

    // 初始化事件监听
    initEventListeners();

    function initEventListeners() {
        // 保存按钮点击事件
        saveBtn.addEventListener('click', async () => {
            console.log('保存按钮被点击'); // 调试日志
            await saveClassInfo();
        });

        // Ctrl+S 快捷键保存
        document.addEventListener('keydown', (e) => {
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault();
                console.log('触发Ctrl+S快捷键'); // 调试日志
                saveClassInfo();
            }
        });
    }

    async function saveClassInfo() {
        // 获取当前描述
        const description = descEdit.value.trim();

        // 获取当前选中的班长ID
        const monitorRadio = document.querySelector('input[name="monitor"]:checked');
        const monitorId = monitorRadio ? parseInt(monitorRadio.value) : null;

        // 构造提交数据
        const formData = {
            description,
            monitor_id: monitorId
        };

        console.log('准备提交数据:', formData); // 调试日志

        try {
            showLoading(true);

            // 发送保存请求
            const response = await fetch(`/teacher/classes/${classId}/update`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCSRFToken()
                },
                body: JSON.stringify(formData)
            });

            console.log('收到服务器响应:', response.status); // 调试日志

            if (!response.ok) throw new Error('网络请求失败');

            const data = await response.json();
            if (data.success) {
                showToast('班级信息已保存', 'success');
                console.log('保存成功'); // 调试日志
            } else {
                throw new Error(data.message || '保存失败，请重试');
            }

        } catch (error) {
            showToast(error.message, 'error');
            console.error('保存过程中发生错误:', error); // 调试日志
        } finally {
            showLoading(false);
        }
    }

    // 显示提示消息
    function showToast(message, type = 'success') {
        const existingToast = document.querySelector('.toast-notification');
        if (existingToast) existingToast.remove();

        const toast = document.createElement('div');
        toast.className = `toast-notification fixed bottom-4 right-4 px-4 py-2 rounded-lg shadow-lg z-50 transition-all duration-300 transform ${
            type === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'
        }`;
        toast.textContent = message;
        document.body.appendChild(toast);

        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateY(-10px)';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    // 显示/隐藏加载状态
    function showLoading(show) {
        const loadingOverlay = document.getElementById('loading-overlay');
        if (show) {
            if (!loadingOverlay) {
                const overlay = document.createElement('div');
                overlay.id = 'loading-overlay';
                overlay.className = 'fixed inset-0 bg-black bg-opacity-20 flex items-center justify-center z-50';
                overlay.innerHTML = `
                    <div class="bg-white p-4 rounded-lg shadow-lg flex items-center">
                        <div class="animate-spin h-6 w-6 border-b-2 border-blue-500 mr-3"></div>
                        <span>保存中...</span>
                    </div>
                `;
                document.body.appendChild(overlay);
            }
        } else {
            loadingOverlay?.remove();
        }
    }

    // 获取CSRF令牌
    function getCSRFToken() {
        const cookies = document.cookie.split('; ');
        for (const cookie of cookies) {
            if (cookie.startsWith('csrf_token=')) {
                return cookie.split('=')[1];
            }
        }
        return '';
    }
});
    </script>
{% endblock %}
